package com.xinbochuang.machine.admin.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MD5Util {
	

	
	private static String  ALGORITHM_PASM="MD5";
	private static int PASM_NUMBER=20;
	private static final Logger logger = LoggerFactory.getLogger(MD5Util.class);
    /**
     * 普通MD5
     */
    public static String MD5(String input) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(ALGORITHM_PASM);
        } catch (NoSuchAlgorithmException e) {
            return "check jdk";
        } catch (Exception e) {
            logger.error(""+e);
            return "";
        }
        char[] charArray = input.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = (md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toUpperCase();
    }

    /**
    * 加盐MD5
     * @return
     */
    public static String generate(String password) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        String salt = sb.toString()+PASM_NUMBER;
        password = md5Hex(password + salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }

    /**
     * 校验加盐后是否和原文一致
     * @param password
     * @param md5
     * @return
     */
    public static boolean verify(String password, String md5) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
            cs2[i / 3] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);
        salt=salt+PASM_NUMBER;
        return md5Hex(password + salt).equals(new String(cs1));
    }

    /**
     * 获取十六进制字符串形式的MD5摘要
     */
    private static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(ALGORITHM_PASM);
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 密码比较
     * @param oldpass
     * @param newpass
     * @return
     */
    public static boolean passEquals(String oldpass,String newpass) {
		if (oldpass.length() > 40) {
			if (!MD5Util.verify(newpass, oldpass)) {
				return false;
			} else {
				return true;
			}
		} else {
			String LoginPass = MD5Util.MD5(newpass);
			if (oldpass.equals(LoginPass)) {
				// 如果密码相等
				return true;
			} else {
				// 如果密码不相等
				return false;
			}
		}
	}
    
    public static void main(String args[]) {
        // 原文
        String plaintext = "123456";
        System.out.println("原始：" + plaintext);
        System.out.println("普通MD5后：" + MD5Util.MD5(plaintext));
        // 获取加盐后的MD5值
        String ciphertext = MD5Util.generate(plaintext);
        String ciphertext2 = MD5Util.generate(plaintext);
        System.out.println("ciphertext: " + ciphertext);
        System.out.println("ciphertext2: " + ciphertext2);

        System.out.println("是否是同一字符串:" + MD5Util.verify("123456", "f72d8791389229a842b4135c89ee9530d615058784c9f21a"));
    }
	
	public static String encrypt(String dataStr) {
		 byte[] hash;
	        try {
	            //创建一个MD5算法对象，并获得MD5字节数组,16*8=128位
	            hash = MessageDigest.getInstance("MD5").digest(dataStr.getBytes("UTF-8"));
	        } catch (NoSuchAlgorithmException e) {
	            throw new RuntimeException("Huh, MD5 should be supported?", e);
	        } catch (UnsupportedEncodingException e) {
	            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
	        }
	        //转换为十六进制字符串
	        StringBuilder hex = new StringBuilder(hash.length * 2);
	        for (byte b : hash) {
	            if ((b & 0xFF) < 0x10) hex.append("0");
	            hex.append(Integer.toHexString(b & 0xFF));
	        }
	        return hex.toString().toUpperCase();
	}

}
